var isLogin = false;
var hostUrl = "https://api.unique0lai.cn";
var notCheckArr = ["login", "reg", "findpass"];
//检测当前是那个页面
function checkPage() {
    console.log($("content").attr('data-now'));
    return $("content").attr('data-now');
}
function addActive(nodes){
    for(var i=0;i<nodes.length;i++){
        nodes[i].classList.add('active');
    }
}
function showPro(message){
    $('#state').html(message);
    $('#prompt-outer').fadeIn();
}
function changeProContent(message){
    $('#state').html(message);
}
function hidePro(){
    
    $('#prompt-outer').fadeOut();
}
function prompt(message) {
    $('#state').html(message);
    $('#prompt-outer').fadeIn();
    setTimeout(function() {
        $('#prompt-outer').fadeOut();
    }, 1300);
};

//清除localstorage中的token等信息
function clearToken() {
    localStorage['token'] = "";
    localStorage['refresh_token'] = "";
    localStorage['expires_in'] = "";
    localStorage['date'] = "";
};
//获取验证码的时间间隔
function captchaInterval(target) {
    var originText = target.html();
    var timeCount = 60;
    target.html(timeCount);
    target.addClass('disabled');
    var interval = setInterval(function() {
        timeCount--;
        target.html(timeCount);
        if (timeCount === 0) {
            clearInterval(interval);
            target.html(originText);
            target.removeClass('disabled');
        }
    }, 1000);
};
//窗口宽度小的时候，首页介绍等导航转到侧栏 
function smallSide(){
    $('#sidebar-btn').on('click',function(){
        if ($(window).width()<=680) {
            $('.small-side').css({left:0});
        }
    });
    $('.close-btn').on('click',function(e){
        $('.small-side').css({left:'-200px'});
    })
}

(function(window) {
    window.geetestObj = { challenge: '', validate: '', seccode: '', status: '' };

    function gt_custom_ajax(result, message) {
        if (result) {
            geetestObj.challenge = $(".geetest_challenge").val();
            geetestObj.validate = $(".geetest_validate").val();
            geetestObj.seccode = $(".geetest_seccode").val();
        }
        console.log(geetestObj);
    }
    window.gt_custom_ajax = gt_custom_ajax;
    window.geetestObj = geetestObj;
})(window);
function funcGetCap (id,$target,method,$http){
    var status,url,data,successText,failText;
    var phoneReg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    var mailReg = /^[^\._-][\w\.-]+@([A-Za-z0-9]+\.)+[A-Za-z]+$/;
    if (method!=='change') {
        if (!geetestObj.challenge||!geetestObj.validate||!geetestObj.seccode) {
            prompt('先完成滑动验证才能获取短信/邮箱验证码');
        }
    }
    if (phoneReg.test(id)) {
        status = "phone";
        if(method!=='change'){
            data = { phone_number: id, method:method ,geetest_challenge: geetestObj.challenge, geetest_validate: geetestObj.validate, geetest_seccode: geetestObj.seccode, status: geetestObj.status };
        }else{
            data = { phone_number: id, method:method };
        }
        url = hostUrl + '/user/send_message/';
        successText = "验证码短信已发送，请查看填写";
        failText = "短信发送失败";
    } else if (mailReg.test(id)) {
        status = "email";
        if(method!=='change'){
            data = { email: id,method:method ,geetest_challenge: geetestObj.challenge, geetest_validate: geetestObj.validate, geetest_seccode: geetestObj.seccode, status: geetestObj.status };
        }else{
            data = { email: id,method:method };
        }
        url = hostUrl + '/user/send_email/';
        successText = "验证码邮件已发送，请查看填写";
        failText = "邮件发送失败";
    } else {
        prompt("邮箱或手机号格式有误");
        return 0;
    }
    if ($target.hasClass('disabled')) {
        return 0;
    }
    captchaInterval($target);
    $http({
        url: url,
        method: 'post',
        data: data
    }).success(function(data) {
        if (data['status'] === 'success') {
            prompt(successText);
        } else {
            prompt(failText);
        }
    }).error(function(data) {
        prompt(failText);
    });
    return status;
};
function getUserInfo($scope,$http){
    if (localStorage['token']) {
        var token = localStorage.getItem('token');
    } else {
        $('#user').hide();
        $('#sidebar .user-info').hide();
        return 0;
    }
    if (notCheckArr.indexOf(checkPage()) < 0) {
        $http({
            url: hostUrl + '/user/info/',
            method: 'get',
            headers: {
                'Authorization': "Token " + token
            }
        }).success(function(data, status) {
            console.log(data);
            console.log(status);
            for (var key in data) {
                localStorage[key] = data[key];
                $scope[key] = data[key];
            }
            $('#loginOrReg').hide();
            if ($(window).width()>760) {
                $('#user').show();
            }
            $('#sidebar .loginOrReg').hide();
            $('#nickname').html(data['username']);
            $scope.commentShow = true;
        }).error(function(data, status) {
            $('#loginOrReg').show();
            $('#user').hide();
            $('#sidebar .user-info').hide();
            if (data['message'] === "invalid token" || status === 401) {
                prompt('错误的用户认证，请重新登录');
                clearToken();
                
            } else {
                prompt("获取用户信息失败");
            }
        })
    }
    $scope.logout = function() {
        clearToken();
        localStorage.QQL = false;
        isLogin = false;
        $('#loginOrReg').show();
        $('#user').hide();
    }
}

//控制sidebar中每一个tab 的打开关闭
function funcToggle(btn,$scope) {
    var toClose = $(btn).parent().parent().siblings();
    for (var i = 0; i < toClose.length; i++) {
        if ($(toClose[i]).hasClass('open')) {
            var toCloseDistance;
            if(!$scope.changeBool && $(toClose[i]).attr('id')==='area-btn'){
                toCloseDistance = $('#server').height();
            }else{
                toCloseDistance = $(toClose[i]).find('.son-menu').height();
            }
            $(toClose[i]).find('.son-menu').css({ 'margin-top': "-" + toCloseDistance + "px", 'opacity': 0 });
            $(toClose[i]).removeClass('open');
        }
    }
    var target
    if(!$scope.changeBool&&$(btn).parent().parent().attr('id')==='area-btn'){
        target = $('#server');
    }else{
        target = $(btn).parent().parent().find('.son-menu');
    }
    
    var closeDistance = target.height();
    var openDistance = $('.one-li-top').height();
    var state = btn.parentNode.parentNode.classList[1];
    target.parent().toggleClass('open');
    if (state === 'open') {
        target.css({ 'margin-top': "-" + closeDistance + "px", 'opacity': 0 });
    } else {
        target.css({ 'margin-top': openDistance + "px", 'opacity': 1 });
    }
}

//根据游戏名来获取区服列表
function getAS(game,tarSonMenu,$http,$scope,func1) {
    tarSonMenu.hide();
    showPro('正在获取区服列表');
    $http({
        // url: hostUrl + '/core/server_lists/',
        url:"/serverList.json",
        method: 'get',
        params: { game: game }
    }).success(function(data) {
        hidePro();
        $scope.changeBool = true;
        $scope.areaServerObj = data[game];
        tarSonMenu.css({ 'margin-top': "-" + tarSonMenu.height() + "px", 'opacity': 0 });
        tarSonMenu.show();
        funcToggle($('#area-open')[0],$scope);
        if(func1){
            func1();
        }
    }).error(function(data) {
        changeProContent('获取区服列表失败');
        hidePro();
    })
}

//初始化极验证
function initG($http) {
    var handler = function(captchaObj) {
        // 弹出式需要绑定触发验证码弹出按钮
        // captchaObj.bindOn("#popup-submit");
        // 将验证码加到id为captcha的元素里
        captchaObj.appendTo("#gt_box");

        // 更多接口参考：http://www.geetest.com/install/sections/idx-client-sdk.html
    };
    $http({
        // 获取id，challenge，success（是否启用failback）
        url: hostUrl + "/captcha/",
        method: "get",
    }).success(function(data) {
        console.log(data);
        var response_str = JSON.parse(data['response_str']);
        geetestObj.status = data['status'];
        var geetest = {};
        for (var key in response_str) {
            if (key === 'success') {
                geetest[key] = !response_str[key];
            } else {
                geetest[key] = response_str[key];
            }
        }
        console.log(geetest);
        geetest.product = 'float';
        initGeetest(geetest, handler);
    });
}


(function() {
    var nowPage = $('content').attr('data-now');
    console.log(nowPage);
    if (nowPage) {
        $('.' + nowPage).addClass('active');
        if (nowPage === 'index'||nowPage === 'coin'||nowPage === 'equip'||nowPage === 'equip-list'||nowPage === 'estimate') {
            $('#logo-area').addClass('active');
            $('#gugu-title img').attr('src', '/static/img/gugu1.png');
            $('#sidebar-btn').on('click', function() {
                if ($('#sidebar').offset()['left'] ===0) {
                    $('#sidebar').css('margin-left','-'+$('#sidebar').width()+'px');
                } else {
                    $('#sidebar').css('margin-left','0px');
                }
            });
        } else if (notCheckArr.indexOf(nowPage) === -1) {
            $('#sidebar-btn').on('click', function() {
                var state = $(this).attr('data-state');
                console.log(state);
                if (state === 'open') {
                    $(this).attr('data-state', 'close');
                    $("#sidebar").css('left', "-" + $("#sidebar").width() + "px");
                    $('#logo-area').removeClass('active');
                } else {
                    $(this).attr('data-state', 'open');
                    $("#sidebar").css('left', "0px");
                    $('#logo-area').addClass('active');
                }
            });
        }
    }

})();
(function() {
    $('#user-list-btn').on('click', function() {
        var target = $('#user-info-entry');
        var userTri = $('#user-tri');
        var state = userTri[0].classList[0];

        console.log(state);
        if (state === 'close') {
            target.show();
            userTri.addClass('open');
            userTri.removeClass('close');
        } else {
            target.hide();
            userTri.addClass('close');
            userTri.removeClass('open');
        }
    });

})();

function sidebarOperation($scope,$http){
    $scope.game = localStorage['game']? localStorage['game']:'地下城与勇士';
    $scope.area = localStorage['area']? localStorage['area']:'北京区';
    $scope.server = localStorage['server']? localStorage['server']:'北京一区'
    $scope.market = "5173";


    //sidebar
    console.log('sidebar');
    $scope.gameList = [];
    $scope.areaServerObj = {};
    $scope.serverList = [];
    $scope.history = [];
    $scope.currentMain = '';
    $scope.changeBool = true;
    $scope.lowExist = true;
    function isEmpty(obj) {
        for (var key in obj) {
            if (key) {
                return false;
            }
        }
        return true;
    }

    $scope.ASFilter = function(item){
        return item.split('(')[0];
    }
    //选择商品种类
    $scope.chooseKind = function ($event) {
        $('#good-btn .son-item').removeClass('active');
        $($event.target).addClass('active');
        if($scope.kind !== $($event.target).attr('data-kind')){
            localStorage.kind = $($event.target).attr('data-kind');
            window.location.href = '/'+ localStorage.kind+'.html';
        }
    }
    
    $scope.toggleOpen = function($event) {
        var btn = $event.target;
        if (btn.parentNode.parentNode.id === "area-btn" && isEmpty($scope.areaServerObj)) {
            prompt('请先选择游戏');
            return 0;
        }
        if (btn.parentNode.parentNode.id === "game-btn" && !$scope.kind) {
            prompt('请先选择商品类别');
            return 0;
        }
        if (btn.parentNode.parentNode.id === "history-btn" && !$scope.history[0]) {
            prompt('暂时没有历史记录');
            return 0;
        }
        funcToggle(btn,$scope);
    };
    
    $scope.getAreaServer = function(game, $event) {
        localStorage.game = game;
        $scope.game = game;
        $scope.server = $scope.area = "";
        var tarSonMenu = $('#area-btn #area');
        
        var nowClick = $event.target;
        $(nowClick).parent().find('.son-item').removeClass('active');
        $(nowClick).addClass('active');
        
        getAS(game,tarSonMenu,$http,$scope);
    };
    //如果localStorage里面有之前选过的游戏区服等，自动获取区服列表
    getAS($scope.game,$('#area-btn #area'),$http,$scope,function(){
        
        $scope.serverList = $scope.areaServerObj[$scope.area];
        setTimeout(function(){
            console.log(document.getElementsByClassName($scope.area))
            addActive(document.getElementsByClassName($scope.area));
            addActive(document.getElementsByClassName($scope.server));
        },200);
    });
    
    
    //获取游戏列表
    $http({
        url: hostUrl + '/core/game_lists/',
        method: 'get'
    }).success(function(data) {
        $scope.gameList = data['games'];
        setTimeout(function () {
            $("#"+$scope.game).addClass('active');
            if($scope.kind==='coin'){
                document.getElementById('魔兽世界（国服）').style.display = 'none';
            }
            if($scope.kind==='equip'||$scope.kind==='equip-list'){
                document.getElementById('天涯明月刀').style.display = 'none';
                document.getElementById('剑侠情缘3').style.display = 'none';
            }

        },300);
        
    }).error(function(data) {
        prompt('获取游戏列表失败');
    });
    $scope.setArea = function(area, $event) {
        localStorage.area = area;
        $scope.area = area;
        var nowClick = $event.target;
        $('.area-item').removeClass('active');
        addActive(document.getElementsByClassName(area));
        $scope.serverList = $scope.areaServerObj[area];
        $('#server').show();
        $scope.changeBool = false;
    };
    $scope.setServer = function(server, $event) {
        localStorage.server = server;
        $scope.server = server;
        var nowClick = $event.target;
        $('.server-item').removeClass('active');
        addActive(document.getElementsByClassName(server));
        $scope.changeBool = true;
        
        if($scope.kind === 'coin'){
            $scope.getGoldInfo();
            $scope.getGoldDeals();
        }else if($scope.kind === 'equip-list'){
            $scope.getEquipList();
        }else if($scope.kind=== 'equip'){
            $scope.getEquipInfo();
            // $scope.getEquipDeals();
        }
    };

    $scope.change = function($event){
        if ($($event.target).attr('data-tar')==='server') {
            $scope.changeBool = false;
        }else{
            $scope.changeBool = true;
        }
    }

    $scope.openPopup = function(){
        $scope.changeBool = false;
        $('.content-main').css('overflow','hidden');
    };
    $scope.closePopup = function(){
        $scope.changeBool = true;
        $('.content-main').css('overflow','auto');
    };
}

function comment($scope,$http){
    $scope.content = "";
    $scope.commentList = [];
    $scope.newComments = [];
    $scope.addComment = function(content){
        var token = localStorage['token'];
        var data;
        if ($scope.equipment) {
            data = {equipment:$scope.equipId,area:$scope.area,server:$scope.server,content:content}
        }else{
            data = {gold:$scope.game,area:$scope.area,server:$scope.server,content:content}
        }
        $http({
            url:hostUrl+'/comment/add_comment/',
            method:'post',
            headers: {
                'Authorization': "Token " + token
            },
            data:data
        }).success(function(data){
            prompt('添加评论成功');
            var dt = new Date();
            $scope.newComments.push({username:$scope.username,content:content,time:dt.getFullYear()+'-'+(dt.getMonth()+1)+'-'+dt.getDate()+'T'+dt.getHours()+':'+dt.getMinutes()+':'+dt.getSeconds()})
        }).error(function(data){

        })
    };
    (function(){
        var data;
        if ($scope.equipment) {
            data = {equipment:$scope.equipId,area:$scope.area,server:$scope.server,page:1}
        }else{
            data = {gold:$scope.game,area:$scope.area,server:$scope.server,page:1}
        }
        $http({
            url:hostUrl+'/comment/get_comment/',
            method:'get',
            params:data
        }).success(function(data){
            $scope.commentList = data['comments'];
            angular.forEach($scope.commentList,function(e,index){
                if((new Date()).getDate()-(new Date(e['time'].split('T')[0])).getDate()<=1){
                    $scope.newComments.push(e);
                }
            })
        })
    })();
    
};
function drawGoldLines(data,$scope){
    var months = {
        'Jan':'1月',
        'Feb':'2月',
        'Mar':'3月',
        'Apr':'4月',
        'May':'5月',
        'Jun':'6月',
        'Jul':'7月',
        'Aug':'8月',
        'Sep':'9月',
        'Oct':'10月',
        'Nov':'11月',
        'Dec':'12月'
    }
    $scope.Lines = $scope.kind==="coin"? {5173:{max:[],min:[],ave:[]},7881:{max:[],min:[],ave:[]}}:{"游戏":{max:[],min:[],ave:[]}}
    
    for(var key in data ){
        var marketArr = data[key];
        angular.forEach(marketArr, function(e, index) {
            var onedate = e[0].split('-');
            var max = [Date.UTC(onedate[0], parseInt(onedate[1])-1, onedate[2]),parseFloat(e[1])];
            var min = [Date.UTC(onedate[0], parseInt(onedate[1])-1, onedate[2]),parseFloat(e[2])];
            var ave = [Date.UTC(onedate[0], parseInt(onedate[1])-1, onedate[2]),parseFloat(e[3])];
            $scope.Lines[key]['max'].push(max);
            $scope.Lines[key]['min'].push(min);
            $scope.Lines[key]['ave'].push(ave);
        });
    };
    console.log($scope.Lines);
    var dataSeries = $scope.kind==="coin"? [{
            name: '5173 最高价',
            data: $scope.Lines['5173']['max']
        }, {
            name: '5173 最低价',
            data: $scope.Lines['5173']['min']
        }, {
            name: '5173 平均价',
            data: $scope.Lines['5173']['ave']
        },{
            name: '7881 最高价',
            data: $scope.Lines['7881']['max']
        },{
            name: '7881 最低价',
            data: $scope.Lines['7881']['min']
        },{
            name: '7881 平均价',
            data: $scope.Lines['7881']['ave']
        },]:[{name:"游戏装备最高价",
            data:$scope.Lines['游戏']['max']},
            {name:"游戏装备最低价",
            data:$scope.Lines['游戏']['min']},
            {name:"游戏装备平均价",
            data:$scope.Lines['游戏']['ave']}]
    $('#pt-chart').highcharts({
        chart: {
            type: 'spline',
            zoomType: 'x',
            events:{
                load:function(event){
                    var labels = document.getElementsByClassName('highcharts-xaxis-labels')[0].getElementsByTagName('tspan');
                    for(var i =0;i<labels.length;i++){
                        var text = $(labels[i]).text();
                        $(labels[i]).text(months[text.split('. ')[1]]+text.split('. ')[0]+'日');
                    };
                    if($scope.method==='week'){
                        $(labels[labels.length-1]).hide();
                    }
                }
            }
        },
        title: {
            text: ''
        },
        
        xAxis: {
            type: 'datetime',
            dateTimeLabelFormats: { // don't display the dummy year
                month: '%b %e',
                year: '%b'
            },
            title: {
                text: 'Date'
            }
        },
        yAxis: {
            title: {
                text: '单位：元/金'
            },
            min: 0
        },
        tooltip: {
            
            borderRadius: 0,
            followPointer: true,
            formatter: function () {
                if($scope.kind==="coin"){
                    var date = new Date(this.x);
                    return this.series.name+'<br>' +'---'+'<br>'+ (date.getMonth()+1)+'月'+date.getDate()+'日：' +
                            this.y + '元/金' ;
                }else{
                    var date = new Date(this.x);
                    var equipAttr = $scope.dateAttr[(date.getMonth()+1)+'月'+date.getDate()+'日'];
                    var attrTemplate = "";
                    for(var key in equipAttr){
                        attrTemplate += key+": "+equipAttr[key]+'<br>';
                    }
                    return this.series.name+'<br>' +'---'+'<br>'+ "属性：" + '<br>' + attrTemplate;
                            
                }
                
            }
        },
        plotOptions: {
            spline: {
                marker: {
                    enabled: true
                }
            }
        },
        series: dataSeries
    });
    
}

//打开index根据 localStorage 中的上次登录时间和保持登录的时间来判断是否需要重新登录
// (function(){
//   if(notCheckArr.indexOf(checkPage())<0){
//     if(localStorage.getItem('date')&&localStorage.getItem('token')){
//       var date = new Date();
//       var lastDate = localStorage.getItem('date');
//       var expires = localStorage.getItem('expires_in');
//       if(date.getTime()>parseInt(lastDate)+(parseInt(expires)*1000)){
//         clearToken();
//         prompt("登录超时，请重新登录");
//         setTimeout(function(){
//           window.location.href= '/login.html';
//         },1000);
//       }else{
//         isLogin = true;
//         localStorage.setItem('date',date.getTime());
//       }
//     }
//     else{
//       isLogin = false;
//       prompt("登录超时，请重新登录");
//       setTimeout(function(){
//         window.location.href= '/login.html';
//       },1000);
//     }
//   }

// })();